package com.shujia.mvc2.dao;

import com.shujia.mvc2.User;

import java.sql.*;

/**
 * 数据库访问层
 * <p>
 * 和数据库交互
 */
public class UserMysqlDao implements UserDao {


    private static Connection con;

    /*
     * 静态代码块
     * 在类加载的时候执行
     *
     */
    static {
        System.out.println("daoMysql实现类");
        try {
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            con = DriverManager.getConnection("jdbc:mysql://node3:3306/shujia", "root", "123456");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 通过用户名查询用户
     * 如果用户存在返回对应的用户名和密码，不存在返回null
     *
     * @param username
     * @return
     */
    public User queryUserByUsername(String username) {

        User user = null;

        //1、加载驱动
        try {

            // 通过用户名查询用户
            PreparedStatement stat = con.prepareStatement("select username,password from user where username=?");

            stat.setString(1, username);

            ResultSet resultSet = stat.executeQuery();

            //解析数据
            if (resultSet.next()) {
                String username1 = resultSet.getString("username");
                String password = resultSet.getString("password");

                user = new User(username1, password);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        //返回

        return user;
    }


    /**
     * 插入一个用户到数据库中
     *
     * @param user
     */

    public void insert(User user) {

        try {
            PreparedStatement stat = con.prepareStatement("insert into user(username,password) values(?,?)");

            stat.setString(1, user.getUsername());
            stat.setString(2, user.getPassword());


            //执行sql
            stat.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }


    public void updatePasswdordByUsername(String username, String newPassword) {
        try {
            PreparedStatement stat = con.prepareStatement("update user set password=? where username=?");

            stat.setString(1, newPassword);
            stat.setString(2, username);

            stat.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}